import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import { View, StyleSheet, TouchableOpacity, Text, Alert } from 'react-native';
import { Icon, SearchBar } from 'react-native-elements';
import OrderList from './components/OrderList';
import { Calendar } from 'react-native-calendars';
import moment from 'moment';
import { primaryColor, screenWidth, toast } from './utils';
import { getDeviceInfo, setPushId } from './clientStorage';
import PushNotification from 'react-native-push-notification';

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  list: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    backgroundColor: '#e1e8ee',
    alignItems: 'center'
  },
  search: {
    width: screenWidth*3/10,
  },
  date: {
    width: screenWidth*3/10,
  },
  statistic: {
    width: screenWidth*4/10,
    flexDirection: 'row'
  },
  button: {
    paddingVertical: 16,
    paddingHorizontal: 8
  },
  buttonSelect: {
    paddingVertical: 16,
    paddingHorizontal: 8,
    backgroundColor: primaryColor,
  },
  dateText: {
    color: primaryColor,
    textAlign: 'center'
  }
});

class JobPage extends Component {
  static navigationOptions = ({navigation, screenProps}) => {
    return {
      title: `Job`,
      tabBarLabel: `Job`,
      tabBarIcon: ({tintColor}) => <Icon name='home' type='font-awesome' color={tintColor} size={24}/>,
      headerRight: (
        <TouchableOpacity onPress={() => navigation.navigate('BagScan', {assignOrder: true})}>
          <Icon style={{marginRight: 16}} name='add' color={primaryColor}/>
        </TouchableOpacity>
      ),
    };
  }
  state = { date: new Date().toString(), calendarOpen: false, filter: 'location' }
  componentDidMount() {
    PushNotification.configure({
      // (optional) Called when Token is generated (iOS and Android)
      onRegister: ({token}) => {
        this.props.updateLoginDevice(token);
      },
      // (required) Called when a remote or local notification is opened or received
      onNotification: ({message, notification, data, params, routeName}) => {
        if (data) {
          if (data.routeName) {
            routeName = data.routeName;
          }
          if (data.params) {
            params = data.params;
          }
        }

        const chinese = this.props.screenProps.chinese;
        let title = chinese?'通知':'Notice';
        if (notification) {
          if (notification.title) {
            title = notification.title;
          }
          if (notification.body) {
            message = notification.body;
          }
        }

        Alert.alert(
          title,
          message,
          [
            {text: chinese?'取消':'Cancel'},
            {text: routeName?(chinese?'更多':'Details'):(chinese?'确定':'OK'), onPress: () => {
              if (routeName) {
                this.props.navigation.navigate(routeName, params);
              }
            }},
          ],
          { cancelable: true }
        );
      },
      // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
      senderID: "690978520618",
      // IOS ONLY (optional): default: all - Permissions to register.
      permissions: {
        alert: true,
        badge: true,
        sound: true
      },
      // Should the initial notification be popped automatically
      // default: true
      popInitialNotification: true,
      /**
        * (optional) default: true
        * - Specified if permissions (ios) and token (android and ios) will requested or not,
        * - if not, you must call PushNotificationsHandler.requestPermissions() later
        */
      requestPermissions: true,
    });
  }
  onToggleCalendar = () => this.setState({calendarOpen: !this.state.calendarOpen})
  onSearchChange = (search) => {
    this.setState({search:search||null, searching: true});
    setTimeout(() => this.setState({searching: false}), 2000);
  }
  onMonthChange = (date) => this.onSelectDate(date, true)
  onSelectDate = ({year, month, day, hour=0}, calendarOpen=false) => {
    const date = moment([year, month-1, day, hour]).toDate().toString();
    this.setState({
      date,
      calendarOpen
    });
    this.props.refetch({date});
  }
  onSelectOrder = (order, action) => {
    if (action==='Collect') {
      this.props.navigation.navigate('CollectOrder', {displayId: order.displayId, orderId: order.id});
    } else if (action==='View') {
      this.props.navigation.navigate('OrderDetail', {displayId: order.displayId, id: order.id});
    }
  }
  onFilterPickup = () => {
    this.setState({filter: 'pickup'});
    toast('Only show pickup orders');
  }
  onFilterDelivery = () => {
    this.setState({filter: 'delivery'});
    toast('Only show delivery orders');
  }
  onFilterLocation = () => {
    this.setState({filter: 'location'});
    toast('Show all orders'); 
  }
  onSms = (orderId) => {
    this.props.navigation.navigate('SendSMS', {orderId});
  }
  isDisabled = () => false
  onUpdateCount = (pickupCount, deliveryCount, locationCount) => this.setState({pickupCount, deliveryCount, locationCount})
  render() {
    const date = moment(this.state.date);
    const select = date.format('YYYY-MM-DD');
    const { pickupCount, deliveryCount, locationCount, filter, search } = this.state;

    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <View style={styles.search}>
            <SearchBar inputStyle={{height:50}} keyboardType='numeric' lightTheme round showLoadingIcon={this.state.searching}
              onChangeText={this.onSearchChange} value={this.state.search} placeholder={this.props.chinese?'查询':'Search'}/>
          </View>
          <View style={styles.date}>
            <TouchableOpacity style={styles.button} onPress={this.onToggleCalendar}>
              <Text style={styles.dateText}>{date.format('MMM Do YYYY')}</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.statistic}>
            <TouchableOpacity style={filter==='pickup'?styles.buttonSelect:styles.button} onPress={this.onFilterPickup}>
              <Text>{`P ${pickupCount||0}`}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={filter==='delivery'?styles.buttonSelect:styles.button} onPress={this.onFilterDelivery}>
              <Text>{`D ${deliveryCount||0}`}</Text>
            </TouchableOpacity>
            <TouchableOpacity style={filter==='location'?styles.buttonSelect:styles.button} onPress={this.onFilterLocation}>
              <Text>{`L ${locationCount||0}`}</Text>
            </TouchableOpacity>
          </View>
        </View>
        <View style={styles.container}>
          {this.state.calendarOpen?
            <Calendar current={select} hideExtraDays selected={[select]} theme={{
              selectedDayBackgroundColor: primaryColor,
              todayTextColor: primaryColor,
              dotColor: primaryColor,
              arrowColor: primaryColor,}}
              onDayPress={this.onSelectDate} isDisabled={this.isDisabled} markedDates={this.props.markedDates}
              onMonthChange={this.onMonthChange} displayLoadingIndicator={this.props.loading}/>
            :<OrderList onSelect={this.onSelectOrder} onDateChagne={this.onDateChagne}
              date={this.state.date} onUpdateCount={this.onUpdateCount} filter={filter}
              search={search} onSms={this.onSms}/>
          }
        </View>
      </View>
    );
  }
}

export default compose(
  graphql(gql`
    mutation updateLoginDevice($device:UserDeviceInput!) {
      updateLoginDevice(device:$device)
    }
  `, {
    name: 'updateLoginDevice',
    props: ({updateLoginDevice}) => {
      return {
        updateLoginDevice: (pushId) => setPushId(pushId)
          .then(() => getDeviceInfo())
          .then(device => updateLoginDevice({variables:{device}}))
      };
    }
  }),
  graphql(gql`
    query JobPage($date:String!,$history:Boolean) {
      workingDays(date:$date,history:$history)
    }
  `, {
    options: () => {
      return {
        variables: {
          date: new Date().toString(),
          history: false
        }
      }
    },
    props: ({data:{workingDays, refetch, loading}}) => {
      let markedDates = {};
      if (workingDays) {
        workingDays.map(date => {
          markedDates[moment(date).format('YYYY-MM-DD')] = {marked: true};
        });
      }

      return {
        markedDates,
        refetch,
        loading
      };
    }
  })
)(JobPage);

